var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
// let index:any={};
var Config = (function () {
    function Config() {
    }
    /**
     * 加载完成时的触发函数
     */
    Config.ready = function () {
    };
    /**
     * 路由失败回调
     */
    Config.routerError = function () {
    };
    /**
     * 路由成功回调
     */
    Config.routerSuccess = function () {
    };
    /**
     * 加载失败回调
     * @param Obj
     * @param Type
     */
    Config.loadError = function (Obj, Type) {
    };
    /**
     * 加载成功回调
     */
    Config.loadSuccess = function () {
    };
    /**
     * 模板加载成功回调
     * @param tpl
     */
    Config.loadTplError = function (tpl) { };
    /**
     * 模板加载成功回调
     * @param tpl
     */
    Config.loadTplSuccess = function (tpl) { };
    Config.login = function () { };
    Config.logout = function () { };
    return Config;
}());
/**
 * HTML 中的对象模式映射表
 * @type {{}}
 */
Config.HTMLMap = {};
/**
 * 登录方法，绑定到index控制器的login方法上
 */
Config.loginFn = function () { };
Config._before_menu = function (m, id) {
};
Config._after_menu = function (m, id) {
};
/**
 * 获取该模式存储的HTML内容
 * @param Obj
 * @param Type
 * @returns {string}
 */
Config.getHTML = function (Obj, Type, Dir) {
    if (Dir === void 0) { Dir = ''; }
    if ((Config.debug == false || window.location.protocol == 'file:') && typeof Config.HTMLMap[Dir] == 'object' && typeof Config.HTMLMap[Dir][Obj] == 'object' && typeof Config.HTMLMap[Dir][Obj][Type] == 'string') {
        return Config.HTMLMap[Dir][Obj][Type];
    }
    else {
        return '';
    }
};
/**
 * 设置HTML内容
 * @param {string} Obj
 * @param {string} Type
 * @param {string} HTML
 */
Config.setHTML = function (Obj, Type, HTML, Dir) {
    if (Dir === void 0) { Dir = ''; }
    if (Config.HTMLMap[Dir] instanceof Object) {
    }
    else {
        Config.HTMLMap[Dir] = {};
    }
    if (Config.HTMLMap[Dir][Obj] instanceof Object) {
    }
    else {
        Config.HTMLMap[Dir][Obj] = {};
    }
    Config.HTMLMap[Dir][Obj][Type] = HTML;
};
/**
 * 退出登录方法
 */
Config.logoutFn = function () { };
Config._initedVM = [];
/**
 * 请求开始的回调，用于显示进度条
 */
Config.requestStart = function () { };
/**
 * 请求结束的回调
 */
Config.requestEnd = function () { };
Config.routerMap = {};
/**
 * 调试开关
 * @type {boolean}
 */
Config.debug = false;
Config.baseUrl = '';
/**
 * ajax服务器地址
 * @type {string}
 */
Config.Host = '';
/**
 * ajax请求入口文件
 * @type {string}
 */
Config.I = 'i';
Config.Root = 'index.php';
Config.DebugRoot = 'd.php';
Config.RequestMethod = 'fetch';
/**
 * 拼接生成ajax请求地址的回调函数
 * @param Obj
 * @param Way
 * @param Module
 * @returns {string}
 */
Config.getRequestUrl = function (Obj, Way, Module) {
    if (Module === void 0) { Module = ''; }
    var req = [
        Obj, Way
    ];
    if (Module.length > 0) {
        req.unshift(Module);
    }
    return (window.location.protocol == 'file:' ? 'http:' : window.location.protocol) + '//' + Config.Host + '/' + (Config.debug === false ? Config.Root : Config.DebugRoot) + '?' + Config.I + '=' + req.join('/') + (Config.debug === false ? '' : "&XDEBUG_SESSION_START=12522");
};
/**
 * 定义vm的加载目录
 * @type {string}
 */
Config.VMDir = 'vm/';
/**
 * 定义vm模板文件的加载地址
 * @type {string}
 */
Config.TPLDir = 'vm/';
/**
 * 当前的导航数据
 * @type {{n: string; e: string; p: string; params: string}}
 */
Config.currentNav = {
    n: "",
    e: "",
    p: "",
    params: ""
};
Config.loaded = [];
Config.index = '';
Config.PageParams = {};
///<reference path="../../DefinitelyTyped/jquery/jquery.d.ts"/>
var Castle;
(function (Castle) {
    var Request = (function () {
        function Request() {
        }
        /**
         * 发送post请求
         * @param url 请求地址
         * @param data 请求数据
         * @param success 成功回调
         * @param error 失败回调
         */
        Request.post = function (url, data, success, error) {
            Request.ajax.apply(this, [url, '', data, success, error]);
        };
        Request.get = function (url, success, error) {
            Request.ajax.apply(this, [url, '', '', success, error]);
        };
        Request.getHtml = function (url, success, error) {
            // if(url.substr(0,4)=='file'){
            var p = /([A-Za-z]{1,})\/([A-Za-z]{1,})_([A-Za-z]{1,})\.html/.exec(url);
            if (p.length == 4) {
                var html = Config.getHTML(p[2], p[3], p[1]);
                if (html.length > 0) {
                    if (success instanceof Function)
                        success.apply(this, [html]);
                    return;
                }
            }
            // }
            var config = {
                method: "GET",
                mode: "cors",
                credentials: "include",
                cache: 'reload'
            };
            var that = this;
            Config.requestStart();
            // Castle.Request.ajax(url,'','',success,error);
            fetch(url, config).then(function (response) {
                Config.requestEnd();
                return response.text();
            }).then(function (d) {
                if ('function' === typeof success)
                    success.apply(that, [d]);
            }).catch(function (err) {
                if ('function' === typeof error)
                    error.apply(that, [err]);
            });
        };
        Request.getJs = function (url, success, error) {
            var config = {
                method: "GET",
                mode: "cors",
                credentials: "include"
            };
            var that = this;
            Config.requestStart();
            fetch(url, config).then(function (response) {
                Config.requestEnd();
                return response.text();
            }).then(function (d) {
                success.apply(that, [d]);
            });
        };
        Request.getCss = function (url) {
            var link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            link.href = url;
            document.getElementsByTagName("head")[0].appendChild(link);
        };
        Request.getStyle = function (cssText) {
            var style = document.createElement("style");
            style.type = "text/css";
            try {
                // firefox、safari、chrome和Opera
                style.appendChild(document.createTextNode(cssText));
            }
            catch (ex) {
            }
            document.getElementsByTagName("head")[0].appendChild(style);
        };
        Request.upload = function (url, selector, data, success, error) {
            // let input: any = document.querySelectorAll(selector);
            var formData = new FormData();
            if ($(selector).val()) {
                $.each($(selector), function (i, v) {
                    var fileList = $(v).get(0).files;
                    for (var x = 0; x < fileList.length; x++) {
                        formData.append('file' + x, fileList.item(x));
                    }
                });
            }
            var host = '';
            fetch(url, {
                method: 'POST',
                // mode: "cors",
                // credentials: "include",
                // headers:{
                //     'Content-Type':'multipart/form-data;charset=utf-8'
                // },
                body: formData
            }).then(function (response) {
                host = response.url.split('/')[2];
                return response.json();
            }).then(function (d) {
                if (d instanceof Object) {
                    if (typeof d.err == "string" && d.err.length > 0) {
                        // 错误
                        if (typeof error == "function")
                            error.apply(this, [d.err, d.c]);
                        else {
                        }
                    }
                    else {
                        if (typeof success == "function")
                            success.apply(this, [d.d]);
                    }
                }
                else if (d instanceof String) {
                }
                else {
                }
            });
        };
        Request.ajax = function (url, get, post, success, error) {
            var that = this;
            var g = {};
            if (get) {
                avalonData.apply(g, [get]);
            }
            var p = {};
            if (post) {
                avalonData.apply(p, [post]);
            }
            var path = Crypt.hex_md5(url + JSON.stringify(g) + JSON.stringify(p));
            if (Castle.Request.request[path]) {
                return;
            }
            else {
                Castle.Request.request[path] = setTimeout(function () {
                    clearTimeout(Castle.Request.request[path]);
                    delete Castle.Request.request[path];
                }, 500);
            }
            var config = {
                url: url,
                type: post ? 'POST' : 'GET',
                data: {},
                success: function (d, status, xhr) {
                    Castle.Request.success.apply(that, [d, xhr, success, error]);
                }, error: function (err) {
                }
            };
            if (post) {
                config.data = {};
                avalonData.apply(config.data, [post]);
            }
            switch (Config.RequestMethod) {
                case 'fetch':
                    config = {
                        mode: "cors",
                        credentials: "include",
                        body: '',
                        method: (post ? "POST" : "GET")
                    };
                    if (post) {
                        var d = {};
                        avalonData.apply(d, [post]);
                        config.body = JSON.stringify(d);
                    }
                    else {
                        delete config.body;
                    }
                    Config.requestStart();
                    var host_1 = '';
                    fetch(url, config).then(function (response) {
                        Config.requestEnd();
                        host_1 = response.url.split('/')[2];
                        return response.json();
                    }).then(function (d) {
                        Castle.Request.success.apply(that, [d, {}, success, error, host_1]);
                    });
                    break;
                case 'jquery':
                    if ($) {
                    }
                    else {
                        loadJs('http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js');
                    }
                    $.ajax(config);
                    break;
                case 'mui':
                    mui.ajax(config);
                    break;
            }
        };
        Request.down = function (options) {
            if (window['jQuery']) {
                var config = $.extend(true, { method: 'post' }, options);
                var $iframe = $('<iframe id="down-file-iframe" />');
                var $form_1 = $('<form target="down-file-iframe" method="' + config.method + '" />');
                $form_1.attr('action', config.url);
                var Data_1 = {}, d = void 0;
                avalonData.apply(Data_1, [config.data]);
                var _loop_1 = function (key) {
                    if (typeof Data_1[key] == 'object')
                        Object.keys(Data_1[key]).forEach(function (k) {
                            $form_1.append('<input type="hidden" name="' + key + '[' + k + ']' + '" value="' + Data_1[key][k] + '" />');
                        });
                    else {
                        d = Data_1[key];
                        $form_1.append('<input type="hidden" name="' + key + '" value="' + d + '" />');
                    }
                };
                for (var key in Data_1) {
                    _loop_1(key);
                }
                $iframe.append($form_1);
                $(document.body).append($iframe);
                $form_1[0].submit();
                $iframe.remove();
            }
            else {
                var rurl = options.url;
                var filename_1 = options.filename;
                delete options.url;
                delete options.filename;
                options = avalon.mix({
                    method: "post",
                    mode: "cors",
                    credentials: "include",
                    data: ''
                }, options);
                if (typeof options.data != 'string') {
                    var d = {};
                    avalonData.apply(d, [options.data]);
                    options.body = JSON.stringify(d);
                    delete options.data;
                }
                // TODO 下载不支持多次下载
                fetch(rurl, options).then(function (res) { return res.blob().then(function (blob) {
                    var a = document.createElement('a');
                    a.href = window.URL.createObjectURL(blob);
                    a.download = filename_1;
                    a.click();
                    window.URL.revokeObjectURL(a.href);
                    a.remove();
                }); });
            }
        };
        Request.ws = function (url) {
            Castle.Request.link[url] = {
                ws: new WebSocketClient(url),
                msg: {},
                url: url
            };
            return Castle.Request.link[url];
        };
        Request.pushConfig = function (url, func) {
            Castle.Request.push[url] = {
                o: this,
                f: func
            };
        };
        /**
         * 发起Websocket请求
         * @param i 请求接口
         * @param d 请求参数
         * @param success 成功回调
         * @param error 错误回调
         * @param t 指定消息编号
         * @param url 要发送的服务器地址，默认为已建立连接的第一个
         * @returns {boolean}
         */
        Request.cmd = function (i, d, success, error, t, url) {
            if (success === void 0) { success = null; }
            if (error === void 0) { error = null; }
            if (t === void 0) { t = ''; }
            if (url === void 0) { url = ''; }
            var wsc = false;
            if (url.length > 5) {
                if (url.substr(-1) != '/')
                    url += '/';
                if (Castle.Request.link[url] == undefined) {
                    wsc = Castle.Request.ws(url);
                }
                else {
                    wsc = Castle.Request.link[url];
                }
            }
            else {
                //取第一个
                if (Object.keys(Castle.Request.link).length > 0) {
                    wsc = Castle.Request.link[Object.keys(Castle.Request.link)[0]];
                }
                else {
                    //TODO 调用系统错误
                    return false;
                }
            }
            if (wsc) {
                var ps = {};
                avalonData.apply(ps, [d]);
                var data = {
                    i: i,
                    d: ps,
                    t: t.length > 0 ? t : (new Date()).valueOf(),
                    m: ''
                };
                if (wsc.msg[data.i + data.t]) {
                    //已存在该消息指令，忽略
                }
                else {
                    //发送指令
                    wsc.ws.send.apply(wsc.ws, [data, wsc.url]);
                    wsc.msg[data.i + data.t] = {
                        success: success,
                        error: error,
                        d: d,
                        o: this
                    };
                }
            }
            else {
            }
        };
        return Request;
    }());
    Request.request = {};
    Request.link = {};
    Request.push = {};
    Request.success = function (d, xhr, success, error, host) {
        if (d instanceof Object) {
            if (host == Config.Host) {
                var UID = 0;
                var UN = '';
                var Groups = [0];
                if (d.UID instanceof String || d.UID instanceof Number || typeof d.UID == 'string' || typeof d.UID == 'number') {
                    UID = Number(d.UID);
                }
                if (d.UN instanceof String || typeof d.UN == 'string') {
                    UN = d.UN;
                }
                if (d.G instanceof Array || d.G instanceof String || typeof d.G == 'string') {
                    if (d.G instanceof String || typeof d.G == 'string') {
                        d.G = d.G.split(',');
                    }
                    for (var x in d.G) {
                        if (d.G[x] && Number(d.G[x])) {
                            Groups.push(Number(d.G[x]));
                        }
                    }
                    if (!Groups.contains(0))
                        Groups.push(0);
                    Groups.uniquelize();
                }
                var p = false;
                for (var i = 0; i < Groups.length; i++) {
                    if (index.user.Groups.indexOf(Groups[i]) < 0) {
                        p = true;
                        break;
                    }
                }
                if (UID != index.user.UID) {
                    index.user.UID = UID;
                }
                if (UN != index.user.UN) {
                    index.user.UN = UN;
                }
                if (p) {
                    index.user.Groups = Groups;
                }
            }
            if ((typeof d.err == "string" && d.err.length > 0)) {
                // 错误
                if (typeof error == "function")
                    error.apply(this, [d.err, d.c]);
                else {
                    console.log(d);
                }
            }
            else {
                if (typeof success == "function")
                    success.apply(this, [d.d, d]);
            }
        }
        else if (typeof d == 'string') {
            if (xhr) {
                if (xhr.responseURL.lastIndexOf('html') > -1) {
                    // html模式
                    success.apply(this, [d]);
                }
                else if (xhr.responseURL.lastIndexOf('js') > -1) {
                }
            }
        }
        else {
        }
    };
    Castle.Request = Request;
    var WebSocketClient = (function () {
        function WebSocketClient(url) {
            this.create(url);
        }
        WebSocketClient.prototype.create = function (url) {
            try {
                this.url = url;
                this.ws = new WebSocket(url);
                this.ws.onclose = function (event) {
                    Castle.Request.link[url].ws.close.apply(Castle.Request.link[url].ws, [event, url]);
                };
                this.ws.onmessage = function (event) {
                    Castle.Request.link[url].ws.receive.apply(Castle.Request.link[url].ws, [event, url]);
                };
                this.ws.onopen = function (event) {
                    Castle.Request.link[url].ws.connect.apply(Castle.Request.link[url].ws, [event, url]);
                };
                this.ws.onerror = function (event) {
                    Castle.Request.link[url].ws.error.apply(Castle.Request.link[url].ws, [event, url]);
                };
            }
            catch (e) {
            }
        };
        WebSocketClient.prototype.error = function (event, url) {
            console.log(event);
        };
        WebSocketClient.prototype.connect = function (event, url) {
            console.log(event);
        };
        WebSocketClient.prototype.close = function (event, url) {
            console.log(event);
            var that = this;
            setTimeout(function () {
                that.create(that.url);
            }, 3000);
        };
        WebSocketClient.prototype.receive = function (event, url) {
            this.dispatch(this.decode(event.data, url), url);
        };
        WebSocketClient.prototype.send = function (data, url) {
            if (this.ws.readyState == this.ws.OPEN)
                this.ws.send(this.encode(data, url) + "\r\n\r\n");
            else {
                var that_1 = this;
                setTimeout(function () {
                    that_1.send(data, url);
                }, 100);
            }
        };
        WebSocketClient.prototype.dispatch = function (data, url) {
            var msg = Castle.Request.link[this.url].msg[data.i + data.t];
            if (msg) {
                Castle.Request.success.apply(msg.o, [data, null, msg.success, msg.error]);
                delete Castle.Request.link[this.url].msg[data.i + data.t];
            }
            else {
                this.push(data, url);
            }
        };
        WebSocketClient.prototype.push = function (data, url) {
            var config = Castle.Request.push[url];
            if (config && typeof config.f == 'function') {
                config.f.apply(config.o, [data]);
            }
        };
        WebSocketClient.prototype.encode = function (data, url) {
            return JSON.stringify(data);
        };
        WebSocketClient.prototype.decode = function (data, url) {
            return JSON.parse(data);
        };
        return WebSocketClient;
    }());
    Castle.WebSocketClient = WebSocketClient;
})(Castle || (Castle = {}));
/**
 * Created by 鄢鹏权 on 2017/05/01.
 */
function clone(obj) {
    var o;
    if (typeof obj == "object") {
        if (obj === null) {
            o = null;
        }
        else {
            if (obj instanceof Array) {
                o = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    o.push(clone(obj[i]));
                }
            }
            else {
                o = {};
                for (var j in obj) {
                    o[j] = clone(obj[j]);
                }
            }
        }
    }
    else {
        o = obj;
    }
    return o;
}
function loadJs(url) {
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = url;
    oHead.appendChild(oScript);
}
function avalonData(obj) {
    if (obj !== undefined && obj !== null) {
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
            if (keys[i].substr(0, 1) != '$')
                if (typeof obj[keys[i]] == 'object') {
                    if (obj[keys[i]] instanceof Array) {
                        this[keys[i]] = [];
                    }
                    else if (obj[keys[i]] instanceof Object) {
                        this[keys[i]] = {};
                    }
                    else { }
                    avalonData.apply(this[keys[i]], [obj[keys[i]]]);
                }
                else {
                    this[keys[i]] = obj[keys[i]];
                }
        }
    }
}
function hereDoc(func) {
    return func.toString().split(/\n/).slice(1, -1).join('\n');
}
/**
 * 获取get参数
 * @param name
 * @returns {any}
 */
function get_query_param(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}
/**
 * 跳转内容
 * @param Obj
 * @param Type
 * @param ID
 * @param Dir
 * @param Params
 */
function goto(Obj, Type, ID, Dir, Params) {
    if (Dir === void 0) { Dir = ''; }
    if (Params === void 0) { Params = {}; }
    if (Type === void 0) {
        Type = '';
    }
    if (ID === void 0) {
        ID = 0;
    }
    if (Dir === void 0) {
        Dir = '';
    }
    if (Params === void 0) {
        Params = {};
    }
    // static s={};
    Config.PageParams = Params;
    if (Obj.slice(0, 1) === '!') {
        //手动传入的
        window.location.hash = Obj;
    }
    else if (Obj.split('/').length > 1) {
        if (Obj.slice(0, 1) != '/') {
            Obj = '/' + Obj;
        }
        window.location.hash = '!' + Obj;
    }
    else if (Obj.length > 0 && Type.length > 0) {
        window.location.hash = '!' + Dir + '/' + Obj + '_' + Type + '/' + ID;
    }
    else if (false === Type) {
        window.location.hash = '!' + Dir + '/' + Obj + '/' + ID;
    }
    else {
        window.location.href = Obj;
    }
}
function menu_click(m, id) {
    if (id === void 0) { id = '0'; }
    if (Config._before_menu instanceof Function) {
        Config._before_menu(m, id);
    }
    if (m.Sub.length == 0)
        goto(m.Obj, m.Type, id);
    if (Config._after_menu instanceof Function) {
        Config._after_menu(m, id);
    }
}
/**
 * Created by 鄢鹏权 on 2017/04/10.
 */
var System = (function () {
    function System(Driver, Config) {
        if (Driver === void 0) { Driver = 'Local'; }
        if (Config === void 0) { Config = {}; }
        // this.handler=new System();
    }
    System.log = function (m) {
        var s = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            s[_i - 1] = arguments[_i];
        }
        s.unshift(m);
        console.log.apply(console, s);
    };
    System.alert = function (m, config) {
        if (config === void 0) { config = {}; }
        alert(m);
    };
    System.notify = function (m, config) {
        if (config === void 0) { config = {}; }
        alert('提示:\r\n' + m);
    };
    System.warning = function (m, config) {
        if (config === void 0) { config = {}; }
        alert('警告:\r\n' + m);
    };
    System.confirm = function (m, ok, cancel, config) {
        if (config === void 0) { config = {}; }
        if (confirm('确认?:\r\n' + m)) {
            if (ok instanceof Function) {
                ok.apply(this, []);
            }
        }
        else {
            if (cancel instanceof Function) {
                cancel.apply(this, []);
            }
        }
    };
    return System;
}());
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */
/*
 * Configurable letiables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var Crypt;
(function (Crypt) {
    var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase        */
    var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
    /*
     * These are the export functions you'll usually want to call
     * They take string arguments and return either hex or base-64 encoded strings
     */
    function hex_md5(s) { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
    Crypt.hex_md5 = hex_md5;
    function b64_md5(s) { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
    Crypt.b64_md5 = b64_md5;
    function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
    Crypt.any_md5 = any_md5;
    function hex_hmac_md5(k, d) { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    Crypt.hex_hmac_md5 = hex_hmac_md5;
    function b64_hmac_md5(k, d) { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    Crypt.b64_hmac_md5 = b64_hmac_md5;
    function any_hmac_md5(k, d, e) { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
    Crypt.any_hmac_md5 = any_hmac_md5;
    /*
     * Perform a simple self-test to see if the VM is working
     */
    function md5_vm_test() {
        return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
    }
    Crypt.md5_vm_test = md5_vm_test;
    /*
     * Calculate the MD5 of a raw string
     */
    function rstr_md5(s) {
        return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
    }
    Crypt.rstr_md5 = rstr_md5;
    /*
     * Calculate the HMAC-MD5, of a key and some data (raw strings)
     */
    function rstr_hmac_md5(key, data) {
        var bkey = rstr2binl(key);
        if (bkey.length > 16)
            bkey = binl_md5(bkey, key.length * 8);
        var ipad = Array(16), opad = Array(16);
        for (var i = 0; i < 16; i++) {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }
        var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
        return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
    }
    Crypt.rstr_hmac_md5 = rstr_hmac_md5;
    /*
     * Convert a raw string to a hex string
     */
    function rstr2hex(input) {
        try {
            hexcase;
        }
        catch (e) {
            hexcase = 0;
        }
        var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
        var output = "";
        var x;
        for (var i = 0; i < input.length; i++) {
            x = input.charCodeAt(i);
            output += hex_tab.charAt((x >>> 4) & 0x0F)
                + hex_tab.charAt(x & 0x0F);
        }
        return output;
    }
    Crypt.rstr2hex = rstr2hex;
    /*
     * Convert a raw string to a base-64 string
     */
    function rstr2b64(input) {
        try {
            b64pad;
        }
        catch (e) {
            b64pad = '';
        }
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var output = "";
        var len = input.length;
        for (var i = 0; i < len; i += 3) {
            var triplet = (input.charCodeAt(i) << 16)
                | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0)
                | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
            for (var j = 0; j < 4; j++) {
                if (i * 8 + j * 6 > input.length * 8)
                    output += b64pad;
                else
                    output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
            }
        }
        return output;
    }
    Crypt.rstr2b64 = rstr2b64;
    /*
     * Convert a raw string to an arbitrary string encoding
     */
    function rstr2any(input, encoding) {
        var divisor = encoding.length;
        var i, j, q, x, quotient;
        /* Convert to an array of 16-bit big-endian values, forming the dividend */
        var dividend = Array(Math.ceil(input.length / 2));
        for (i = 0; i < dividend.length; i++) {
            dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
        }
        /*
         * Repeatedly perform a long division. The binary array forms the dividend,
         * the length of the encoding is the divisor. Once computed, the quotient
         * forms the dividend for the next step. All remainders are stored for later
         * use.
         */
        var full_length = Math.ceil(input.length * 8 /
            (Math.log(encoding.length) / Math.log(2)));
        var remainders = Array(full_length);
        for (j = 0; j < full_length; j++) {
            quotient = Array();
            x = 0;
            for (i = 0; i < dividend.length; i++) {
                x = (x << 16) + dividend[i];
                q = Math.floor(x / divisor);
                x -= q * divisor;
                if (quotient.length > 0 || q > 0)
                    quotient[quotient.length] = q;
            }
            remainders[j] = x;
            dividend = quotient;
        }
        /* Convert the remainders to the output string */
        var output = "";
        for (i = remainders.length - 1; i >= 0; i--)
            output += encoding.charAt(remainders[i]);
        return output;
    }
    Crypt.rstr2any = rstr2any;
    /*
     * Encode a string as utf-8.
     * For efficiency, this assumes the input is valid utf-16.
     */
    function str2rstr_utf8(input) {
        var output = "";
        var i = -1;
        var x, y;
        while (++i < input.length) {
            /* Decode utf-16 surrogate pairs */
            x = input.charCodeAt(i);
            y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
            if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
                x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
                i++;
            }
            /* Encode output as utf-8 */
            if (x <= 0x7F)
                output += String.fromCharCode(x);
            else if (x <= 0x7FF)
                output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F));
            else if (x <= 0xFFFF)
                output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F));
            else if (x <= 0x1FFFFF)
                output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F));
        }
        return output;
    }
    Crypt.str2rstr_utf8 = str2rstr_utf8;
    /*
     * Encode a string as utf-16
     */
    function str2rstr_utf16le(input) {
        var output = "";
        for (var i = 0; i < input.length; i++)
            output += String.fromCharCode(input.charCodeAt(i) & 0xFF, (input.charCodeAt(i) >>> 8) & 0xFF);
        return output;
    }
    Crypt.str2rstr_utf16le = str2rstr_utf16le;
    function str2rstr_utf16be(input) {
        var output = "";
        for (var i = 0; i < input.length; i++)
            output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF);
        return output;
    }
    Crypt.str2rstr_utf16be = str2rstr_utf16be;
    /*
     * Convert a raw string to an array of little-endian words
     * Characters >255 have their high-byte silently ignored.
     */
    function rstr2binl(input) {
        var output = Array(input.length >> 2);
        for (var i = 0; i < output.length; i++)
            output[i] = 0;
        for (var i = 0; i < input.length * 8; i += 8)
            output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
        return output;
    }
    Crypt.rstr2binl = rstr2binl;
    /*
     * Convert an array of little-endian words to a string
     */
    function binl2rstr(input) {
        var output = "";
        for (var i = 0; i < input.length * 32; i += 8)
            output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
        return output;
    }
    Crypt.binl2rstr = binl2rstr;
    /*
     * Calculate the MD5 of an array of little-endian words, and a bit length.
     */
    function binl_md5(x, len) {
        /* append padding */
        x[len >> 5] |= 0x80 << ((len) % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;
        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;
        for (var i = 0; i < x.length; i += 16) {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;
            a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
            d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
            b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
            d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
            c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
            d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
            d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
            a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
            d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
            c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
            b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
            d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
            c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
            d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
            c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
            a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
            d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
            c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
            b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
            a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
            d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
            b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
            d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
            c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
            d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
            a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
            d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
            b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
            a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
            d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
            c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
            d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
            d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
            a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
            d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
            b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
        }
        return Array(a, b, c, d);
    }
    Crypt.binl_md5 = binl_md5;
    /*
     * These export functions implement the four basic operations the algorithm uses.
     */
    function md5_cmn(q, a, b, x, s, t) {
        return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
    }
    Crypt.md5_cmn = md5_cmn;
    function md5_ff(a, b, c, d, x, s, t) {
        return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }
    Crypt.md5_ff = md5_ff;
    function md5_gg(a, b, c, d, x, s, t) {
        return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }
    Crypt.md5_gg = md5_gg;
    function md5_hh(a, b, c, d, x, s, t) {
        return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }
    Crypt.md5_hh = md5_hh;
    function md5_ii(a, b, c, d, x, s, t) {
        return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }
    Crypt.md5_ii = md5_ii;
    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    function safe_add(x, y) {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }
    Crypt.safe_add = safe_add;
    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    function bit_rol(num, cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    Crypt.bit_rol = bit_rol;
})(Crypt || (Crypt = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
///<reference path="Config.ts"/>
///<reference path="Request.ts"/>
///<reference path="Common.ts"/>
///<reference path="System.ts"/>
///<reference path="md5.ts"/>
var Avalon;
(function (Avalon) {
    var VM = (function () {
        function VM(id, ObjName, ModuleName) {
            if (id === void 0) { id = ''; }
            if (ObjName === void 0) { ObjName = ''; }
            if (ModuleName === void 0) { ModuleName = ''; }
            this.$id = '';
            this.PageRange = 5;
            /**
             * 对象名称
             * @type {string}
             */
            this.$ObjName = '';
            /**
             * 模块名称
             * @type {string}
             */
            this.$ModuleName = '';
            /**
             * 主键，默认为对象名称+ID
             * @type {string}
             */
            this.$PK = '';
            /**
             * 限定返回属性范围，支持数组末位为false时反选
             * @type {boolean}
             */
            this.Properties = false;
            this.html = '';
            /**
             * 配置是否在搜索时输出报表数据
             * @type {boolean}
             */
            this.SearchReport = false;
            /**
             * 显示结果
             * @type {{}}
             */
            this.Data = {};
            this.index = {
                DataIndex: -1,
                AddDataIndex: -1,
                EditDataIndex: -1
            };
            /**
             * 添加模式的数据
             * @type {{}}
             */
            this.AddData = {};
            /**
             * 重置添加数据的原始模型
             * @type {{}}
             */
            this.$AddData = {};
            /**
             * 编辑数据的数据模型
             * @type {{}}
             */
            this.EditData = {};
            this.$EditDataFields = [];
            this.$AddDataFields = [];
            /**
             * 重置编辑数据的数据模型
             * @type {{}}
             */
            this.$EditData = {};
            this.$FieldConf = {};
            /**
             * 字典表
             * @type {{}}
             */
            this.DICs = {};
            /**
             * 字典数据的配置信息
             * @type {{}}
             */
            this.$DICsConf = {};
            /**
             * gets获取的结果集
             * @type {Array}
             */
            this.List = [];
            /**
             * 用于search接口的排序规则参数
             * @type {string}
             */
            this.Sort = "";
            /**
             * 搜索接口的返回结构，在页面渲染时可以适用for来遍历@Search.L
             * @type Search {{L: Array; P: number; N: number; T: number; Pages: Array}}
             */
            this.Search = {
                L: [], P: 1, N: 10, T: 0, Pages: [], TP: 0, R: {}
            };
            /**
             * 筛选条件
             */
            this.Where = {};
            /**
             * 模糊搜索的关键词，请适用ms-duplex指令来绑定到input输入框
             * @type {string}
             */
            this.Keyword = '';
            /**
             * 默认搜索值
             * @type {{}}
             */
            this.$Where = {};
            /**
             * 报表内容
             * @type {{L: Array; P: number; N: number; T: number; R: {}}}
             */
            this.Report = {
                L: [], P: 1, N: 10, T: 0, R: {}, Pages: []
            };
            /**
             * 模式
             * @type {string}
             */
            this.Type = '';
            this.SelfTPL = {
                'Detail': '__OBJ__/__OBJ_____TYPE__.html',
                'Add': '__OBJ__/__OBJ_____TYPE__.html',
                'Edit': '__OBJ__/__OBJ___Edit.html',
            };
            /**
             * 获得输入框时间
             * @param {string} time
             * @returns {any}
             */
            this.getInputTime = function (time) {
                if (time === void 0) { time = ''; }
                var date = time.length > 0 ? new Date(time) : new Date();
                return date.format('yyyy-MM-ddThh:mm');
            };
            /**
             * 在vm模式切换后的回掉函数，
             * @param n 新值
             * @param o 旧值
             * @param html
             * @private
             */
            this._after_type_change = function (n, o, html) {
            };
            /**
             * 加载完成后的回调
             * @param n
             * @param p
             * @param type
             * @private
             */
            this._after_ready = function (n, p, type) { };
            /**
             * 加载前的回调
             * @param n
             * @param p
             * @param type
             * @private
             */
            this._before_ready = function (n, p, type) { };
            /**
             * 重置输入模型，如重置搜索条件则参数为 Where
             * @param param
             */
            this.reset = function (param) {
                if (this[param] && this['$' + param]) {
                    this[param] = avalon.mix(this['$' + param]);
                }
            };
            /**
             * 发起添加请求，默认为当前vm的AddData
             * @param Data
             * @param success
             * @param error
             * @constructor
             */
            this.DoAdd = function (Data, success, error) {
                if (Data === void 0) { Data = false; }
                if (success === void 0) { success = false; }
                if (error === void 0) { error = false; }
                if ((Data.clientX > 0 && Data.clientY > 0) || false === Data) {
                    Data = this.AddData;
                }
                var ad = {};
                avalonData.apply(ad, [Data]);
                // TODO 执行参数校验
                this.do_add(ad, success, error);
            };
            /**
             * 发起存储请求
             * @param ID 对象主键编号
             * @param Data 对象数据
             * @constructor
             */
            this.DoSave = function (ID, Data) {
                if (ID === void 0) { ID = false; }
                if (Data === void 0) { Data = false; }
                if (Data === false) {
                    Data = this.EditData;
                }
                if ((ID.clientX > 0 && ID.clientY > 0) || false === ID) {
                    ID = this.EditData[this.$PK];
                }
                if (ID > 0) {
                    var ad = {};
                    avalonData.apply(ad, [Data]);
                    // TODO 执行参数校验
                    this.do_save(ID, ad);
                }
                else {
                }
            };
            /**
             * 发起删除请求
             * @param ID 对象主键编号
             * @param Index
             * @constructor
             */
            this.DoDel = function (ID, Index) {
                if (ID === void 0) { ID = false; }
                if (Index === void 0) { Index = false; }
                if (Index === false) {
                    Index = this.EditData;
                }
                if ((ID.clientX > 0 && ID.clientY > 0) || false === ID) {
                    ID = this.EditData[this.$PK];
                }
                this.do_del(ID);
            };
            /**
             * 刷新列表数据，在刷新按钮上使用 :click="@DoRefresh"
             * @constructor
             */
            this.DoRefresh = function () {
                this.do_search();
            };
            /**
             * List模式时调用
             */
            this.ready_List = function (n, p, type) {
                this.Type = 'List';
                this.html = '';
                // this._before_ready_List(n,p,type);
                this.Search.P = n;
                this.do_search();
                // this._after_ready_List(n,p,type);
            };
            this._after_ready_List = function (n, p, type) { };
            this._before_ready_List = function (n, p, type) { };
            /**
             * Detail模式的初始化回调
             * @param n
             * @param p
             * @param type
             */
            this.ready_Detail = function (n, p, type) {
                if (n > 0) {
                    var NeedGet_1 = true;
                    var that_2 = this;
                    avalon.each(this.Search.L, function (i, v) {
                        if (v[that_2.$PK] == n) {
                            that_2.Data = v;
                            NeedGet_1 = false;
                            return false;
                        }
                    });
                    if (NeedGet_1)
                        this.do_get(n);
                }
                else
                    history.back();
            };
            /**
             * 返回上一个路由
             */
            this.back = function () {
                history.back();
            };
            /**
             * add模式的初始化回调
             * @param n
             * @param p
             * @param type
             */
            this.ready_Add = function (n, p, type) {
                this.AddData = clone(this.$AddData);
            };
            /**
             * 编辑状态的初始化回调
             * @param n
             * @param p
             * @param type
             */
            this.ready_Edit = function (n, p, type) {
                if (n > 0) {
                    var NeedGet_2 = true;
                    var that_3 = this;
                    avalon.each(this.Search.L, function (i, v) {
                        if (v[that_3.$PK] == n) {
                            that_3.Data = v;
                            NeedGet_2 = false;
                            return false;
                        }
                    });
                    if (NeedGet_2)
                        this.do_get(n);
                }
                else
                    history.back();
            };
            /**
             * 获取一个对象
             * @param ID
             */
            this.do_get = function (ID) {
                var req = {
                    Properties: this.Properties
                };
                req[this.$PK] = ID;
                if (false === this._before_do_get(req)) {
                    return;
                }
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'get', this.$ModuleName), req,
                    function (d, s) {
                        this._after_do_get(d);
                        this._object_format(d);
                        this.Data = d;
                    }]);
            };
            this._after_do_get = function (d) { };
            this._before_do_get = function (req) { };
            /**
             * 添加对象
             * @param Obj
             */
            this.do_add = function (Obj, next, success, error) {
                if (next === void 0) { next = ''; }
                if (success === void 0) { success = false; }
                if (error === void 0) { error = false; }
                //TODO 检查判断逻辑，执行参数校验
                if (false === this._before_do_add(Obj)) {
                    return;
                }
                Castle.Request.post.apply(this, [
                    Config.getRequestUrl(this.$ObjName, 'add', this.$ModuleName),
                    Obj,
                    function (d, s) {
                        this._object_format(d);
                        this._after_do_add(d);
                        this.Data = d;
                        this.AddData = clone(this.$AddData);
                        if (typeof success == 'function') {
                            success.apply(this, [d, s]);
                        }
                        if (next.length > 0) {
                            this.Type = next;
                        }
                        this.do_search();
                    },
                    function (e) {
                        if (typeof error == 'function')
                            error.apply(this, [e, Obj]);
                    }
                ]);
            };
            this._after_do_add = function (d) { };
            this._before_do_add = function (req) { };
            /**
             * 根据ID删除
             * @param ID
             */
            this.do_del = function (ID, success, error) {
                if (success === void 0) { success = false; }
                if (error === void 0) { error = false; }
                var req = {};
                req[this.$PK] = ID;
                if (false === this._before_do_del(req)) {
                    return;
                }
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'del', this.$ModuleName), req,
                    function (d, s) {
                        this._after_do_del(d);
                        this.do_search();
                        if (typeof success == 'function') {
                            success.apply(this, [d]);
                        }
                    }]);
            };
            this._after_do_del = function (d) { };
            this._before_do_del = function (req) { };
            /**
             * 对象格式化回调，该回调会在get/gets/search后被回调，用于格式化本地数据
             * @param obj
             * @private
             */
            this._object_format = function (obj) { };
            this._parse_where = function () {
                var req = {
                    Keyword: this.Keyword,
                    W: {},
                    P: this.Search.P > 0 ? this.Search.P : 1,
                    N: this.Search.N,
                    Sort: this.Sort,
                    Properties: this.Properties,
                    R: this.SearchReport
                };
                avalonData.apply(req.W, [this.Where]);
                for (var x in req.W) {
                    var s = /\{[a-zA-Z]+\}/g.exec(req.W[x]);
                    if (s && s.length > 0) {
                        switch (s[0].toUpperCase()) {
                            case "{UID}":
                                req.W[x] = index.user.UID;
                                break;
                        }
                    }
                    if (req.W[x] === "") {
                        delete req.W[x];
                    }
                }
                return req;
            };
            /**
             * 条件搜索
             */
            this.do_search = function () {
                var req = this._parse_where();
                if (false === this._before_do_search(req)) {
                    return;
                }
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'search', this.$ModuleName), req,
                    function (d, s) {
                        if (d.L.length == 0 && d.T > 0 && d.N > 0 && d.P) {
                            this.Search.P = 1;
                            return;
                        }
                        this._after_do_search(d);
                        var that = this;
                        d.L.forEach(function (v, i, a) {
                            that._object_format(v);
                        });
                        d.Pages = [];
                        var TotalPage = Number(d.T / d.N);
                        if (TotalPage > Math.floor(TotalPage)) {
                            TotalPage += 1;
                        }
                        d.TP = Math.floor(TotalPage);
                        var Start = this.Search.P < 3 ? 1 : this.Search.P - 2;
                        var End = TotalPage > 5 ? Start + 5 : TotalPage;
                        for (var x = Start; x <= End; x++) {
                            d.Pages.push(x);
                        }
                        // if(d.T%d.N>0){d.Pages.push(d.Pages.length+1)}
                        this.Search = d;
                    }]);
            };
            this._before_do_search = function (req) { };
            this._after_do_search = function (d) { };
            /**
             * 获取指定对象数据
             * @param IDs
             */
            this.do_gets = function (IDs) {
                var req = {
                    Properties: this.Properties
                };
                req[this.$PK + 's'] = IDs;
                if (false === this._before_do_gets(req)) {
                    return;
                }
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'gets', this.$ModuleName), req,
                    function (d, s) {
                        var that = this;
                        this._after_do_gets(d);
                        d.forEach(function (v, i, a) {
                            that._object_format(v);
                        });
                        this.List = d;
                    }]);
            };
            this._before_do_gets = function (req) { };
            this._after_do_gets = function (d) { };
            this._type_change = function (n, o) {
            };
            /**
             * 调用save操作
             * @param ID 对象编号
             * @param Params 要存储的对象属性
             */
            this.do_save = function (ID, Params, next, success, error) {
                if (next === void 0) { next = ''; }
                if (success === void 0) { success = false; }
                if (error === void 0) { error = false; }
                var req = {
                    Properties: this.Properties,
                    Params: Params
                };
                req[this.$PK] = ID;
                if (this.$EditDataFields.length > 0) {
                    var other_1 = this.$EditDataFields[this.$EditDataFields.length - 1] === true;
                    var keep_1 = {};
                    this.$EditDataFields.forEach(function (v) {
                        if (other_1) {
                            //删除这些
                            delete req.Params[v];
                        }
                        else {
                            //保留这些
                            keep_1[v] = req.Params[v] ? req.Params[v] : '';
                        }
                    });
                    if (false === other_1) {
                        req.Params = keep_1;
                    }
                }
                if (false === this._before_do_save(req)) {
                    return;
                }
                var that = this;
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'save', this.$ModuleName), req,
                    function (d, s) {
                        if (false === that._after_do_save(req, d)) {
                            return;
                        }
                        if (typeof success == 'function') {
                            success.apply(that, [d, s]);
                        }
                        if (next.length > 0) {
                            this.Type = next;
                        }
                    }]);
            };
            this._before_do_save = function (req) {
            };
            this._after_do_save = function (req, d) {
            };
            /**
             * 报表
             * @param Name
             * @param Params
             * @param Down
             */
            this.do_report = function (Name, Params, Down) {
                if (Params === void 0) { Params = {}; }
                if (Down === void 0) { Down = false; }
                var req = {
                    Name: Name,
                    Down: Down
                };
                req = avalon.mix(req, Params);
                if (Down) {
                    Castle.Request.down({
                        url: Config.getRequestUrl(this.$ObjName, 'report', this.$ModuleName),
                        data: req
                    });
                }
                else {
                    Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, 'report', this.$ModuleName), req,
                        function (d, s) {
                            this.Report = d;
                        }]);
                }
            };
            /**
             * 发起其它请求
             * @param i
             * @param Params
             * @param success
             * @param error
             */
            this.do_other = function (i, Params, success, error) {
                Castle.Request.post.apply(this, [Config.getRequestUrl(this.$ObjName, i, this.$ModuleName), Params,
                    success, error]);
            };
            this.DataWhere = {};
            this.DataReport = {
                L: [], P: 1, N: 10, T: 0, R: {}, Pages: []
            };
            /**
             * 获取报表数据
             * @param Obj
             * @param Name
             * @param Params
             */
            this.report = function (Obj, Name, Params) {
                Castle.Request.post.apply(this, [Config.getRequestUrl(Obj, 'report'), {
                        Name: Name,
                        Params: Params
                    }, function (d) {
                        this.DataReport = d;
                    }, function (e) {
                        System.warning('获取报表发生错误');
                    }]);
            };
            this.$id = id;
            this.$ObjName = ObjName.length > 0 ? ObjName : id;
            this.$ModuleName = ModuleName;
            if (!window[this.$ObjName + 'VM']) {
                window[this.$ObjName + 'VM'] = this;
            }
        }
        /**
         * 初始化
         */
        VM.prototype.init = function () {
            var that = this;
            var timeout = null;
            var time = 0;
            this.$watch('Type', function (n, o) {
                if (that.SelfTPL[n]) {
                    var doc = Config.TPLDir + that.SelfTPL[n].replace(/__OBJ__/g, that.$ObjName).replace(/__TYPE__/g, n);
                    if (Config.debug) {
                        doc = doc + '?v' + new Date().getTime();
                    }
                    var html = Config.getHTML(that.$ObjName, n, that.$ObjName);
                    if (html.length > 0) {
                        window[that.$ObjName + 'VM'].html = html;
                        that._after_type_change(n, o, html);
                    }
                    else {
                        Castle.Request.getHtml(doc, function (html) {
                            window[that.$ObjName + 'VM'].html = html;
                            that._after_type_change(n, o, html);
                        });
                    }
                }
                that._type_change(n, o);
                // if(that['ready_'+n] instanceof Function){
                //     that['ready_'+n].apply(that,[0,{}])
                // }
            });
            if (this.$ObjName == "") {
                this.$ObjName = this.$id;
            }
            var reloadSearch = function (n, o) {
                time++;
                if (n == o || time < 3)
                    return;
                if (timeout) {
                    window.clearTimeout(timeout);
                }
                timeout = window.setTimeout(function () {
                    that.do_search();
                    timeout = null;
                }, 200);
            };
            this.$watch('Search.P', reloadSearch);
            this.$watch('Search.N', reloadSearch);
            this.$watch('Keyword', reloadSearch);
            // let that = this;
            avalon.each(this.Where, function (i, v) {
                that.$watch('Where.' + i, function (n, o) {
                    if ("" === n) {
                        if (that.$Where[i]) {
                            that.Where[i] = that.$Where[i];
                            // n=that.$Where[i];
                        }
                    }
                    if (that._where_change('Where.' + i, n, o) === true) {
                        reloadSearch(n, o);
                    }
                });
            });
            var AddDataKeys = Object.keys(this.AddData);
            var $AddDataKeys = Object.keys(this.$AddData);
            if (AddDataKeys.length > 6 && $AddDataKeys.length == 0) {
                var p = {};
                avalonData.apply(p, [this.AddData]);
                this.$AddData = p;
            }
            if (AddDataKeys.length == 6 && $AddDataKeys.length >= 0) {
                this.AddData = this.$AddData;
            }
            var EditDataKeys = Object.keys(this.EditData);
            var $EditDataKeys = Object.keys(this.$EditData);
            if (EditDataKeys.length > 6 && $EditDataKeys.length == 0) {
                var p = {};
                avalonData.apply(p, [this.EditData]);
                this.$EditData = p;
            }
            if (EditDataKeys.length == 6 && $EditDataKeys.length >= 0) {
                this.EditData = this.$EditData;
            }
            this.init_DICs();
        };
        /**
         * where数组发生变化时的回掉函数，编写逻辑判断是否应该重新刷新数据
         * @param Field
         * @param n
         * @param o
         * @returns {boolean}
         * @private
         */
        VM.prototype._where_change = function (Field, n, o) {
            return true;
        };
        /**
         * vm加载就绪
         * @param n
         * @param p
         * @param type
         */
        VM.prototype.ready = function (n, p, type) {
            this._before_ready(n, p, type);
            if (this.$PK.length < 1) {
                this.$PK = this.$ObjName + 'ID';
            }
            this._after_ready(n, p, type);
        };
        /**
         * 重置搜索参数
         */
        VM.prototype.reset_search = function () {
            this.Where = this.$Where;
            this.Keyword = '';
        };
        /**
         * 初始字典数据
         */
        VM.prototype.init_DICs = function () {
        };
        return VM;
    }());
    Avalon.VM = VM;
    var Components = (function () {
        function Components() {
            this.template = '';
            this.defaults = {
                /**
                 * 组件被加载时触发
                 * @param vm
                 */
                onInit: function (vm) {
                },
                /**
                 * 组件就绪时触发
                 * @param vm
                 */
                onReady: function (vm) {
                }
            };
        }
        return Components;
    }());
    Avalon.Components = Components;
})(Avalon || (Avalon = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
var Castle;
(function (Castle) {
    var Cache = (function () {
        function Cache() {
        }
        Cache.set = function (key, value) {
            window.localStorage.setItem(key, value);
        };
        Cache.get = function (key) {
            return window.localStorage.getItem(key);
        };
        Cache.getSet = function (key, value) {
            var s = this.get(key);
            this.set(key, value);
            return s;
        };
        Cache.del = function (key) {
            window.localStorage.removeItem(key);
        };
        Cache.getDel = function (key) {
            var s = this.get(key);
            this.del(key);
            return s;
        };
        Cache.clear = function () {
            window.localStorage.clear();
        };
        return Cache;
    }());
    Castle.Cache = Cache;
})(Castle || (Castle = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
var Castle;
(function (Castle) {
    var Cookie = (function () {
        function Cookie() {
        }
        Cookie.set = function (name, value) {
            var Days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toTimeString();
        };
        Cookie.get = function (name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return decodeURI(arr[2]);
            else
                return null;
        };
        Cookie.clear = function () {
            document.cookie = '';
        };
        return Cookie;
    }());
    Castle.Cookie = Cookie;
})(Castle || (Castle = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
var Menu;
(function (Menu_1) {
    // export enum Type{
    //     DIR="1",
    //     EDIT='1',
    //     ADD='1',
    //     LIST='1',
    //     DETAIL='1',
    // }
    var Menu = (function () {
        function Menu() {
        }
        Menu.add = function (item) {
            this.menu.push(item);
        };
        Menu.removeByTitle = function (Title) {
            // avalon.each
        };
        return Menu;
    }());
    Menu.menu = [];
    Menu_1.Menu = Menu;
    var Item = (function () {
        function Item(Title, Obj, Group, Type, Sub, Class, Attr, Show, Html, Params) {
            if (Group === void 0) { Group = [0]; }
            if (Type === void 0) { Type = "DIR"; }
            if (Sub === void 0) { Sub = []; }
            if (Class === void 0) { Class = ''; }
            if (Attr === void 0) { Attr = {}; }
            if (Show === void 0) { Show = true; }
            if (Html === void 0) { Html = ''; }
            if (Params === void 0) { Params = {}; }
            this.Title = ''; //标题
            this.Obj = ''; //对象名称
            this.Type = ''; //模式 DIR/EDIT/ADD/LIST/DETAIL
            this.Sub = []; //子目录
            this.Group = []; //权限组
            this.Show = true;
            this.Class = '';
            this.Html = '';
            this.Attr = {};
            this.Params = {};
            this.DOM = '';
            this.Title = Title;
            this.Obj = Obj;
            this.Sub = Sub;
            this.Group = Group;
            this.Show = Show;
            this.Type = Type;
            this.Html = Html;
            this.Class = Class;
            this.Attr = Attr;
            this.Params = Params;
        }
        return Item;
    }());
    Menu_1.Item = Item;
})(Menu || (Menu = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
///<reference path="Config.ts"/>
///<reference path="Menu.ts"/>
var Avalon;
(function (Avalon) {
    var Index = (function (_super) {
        __extends(Index, _super);
        function Index() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.$id = 'index';
            _this.head = {};
            _this.Header = {
                Title: ''
            };
            _this.headHtml = "";
            _this.contentHtml = "";
            _this.footHtml = "";
            _this.Control = {
                ShowNav: true,
                ShowMenu: true,
                ShowMessage: false,
                ShowNotification: false,
                ShowTask: false
            };
            _this.messages = [];
            _this.notifications = [];
            _this.tasks = [];
            _this.login = false; //是否登录
            _this.user = {
                Src: '//cdn.bootcss.com/admin-lte/2.3.11/img/user2-160x160.jpg',
                Name: '',
                Memo: '',
                Small: '',
                UN: '',
                UID: '',
                Status: {
                    Text: '',
                },
                Menus: [
                    {
                        Title: '离开',
                        Href: 'out'
                    }
                ],
                Groups: [0],
                Sex: ''
            };
            _this.loginInput = {
                Account: "",
                PWD: ""
            };
            _this.loginFn = function () {
                Config.loginFn();
            };
            _this.logoutFn = function () {
                Config.logoutFn();
            };
            _this.menu = [];
            return _this;
        }
        Index.prototype.ready = function (n, p) {
            Config.ready();
            Avalon.Router.ready();
        };
        return Index;
    }(Avalon.VM));
    Avalon.Index = Index;
})(Avalon || (Avalon = {}));
var index = avalon.define(new Avalon.Index());
index.$watch('user.UID', function (n, o) {
    if (Number(n) > 0) {
        Config.login();
    }
    else {
        Config.logout();
    }
});
avalon.ready(function () {
    index.menu = clone(Menu.Menu.menu);
    index.ready();
    avalon.scan(document.getElementsByTagName('html')[0]);
});
/**
 * Created by 鄢鹏权 on 2017/04/26.
 */
var Avalon;
(function (Avalon) {
    var Report = (function () {
        function Report() {
            this.$id = 'Report';
            this.Type = '';
            this.DICs = {};
            this.Where = {};
            this.Report = {};
            this.Config = {};
            this.init_DICs = function () {
            };
            this.init = function () {
                this.init_DICs();
            };
            this.ready = function (n, p) {
            };
            this.report = function (Obj, Name, Params) {
                Castle.Request.post.apply(this, [Config.getRequestUrl(Obj, 'report'), {
                        Name: Name,
                        Params: Params
                    }, function (d) {
                        if (this.Report[Obj] == undefined) {
                            this.Report[Obj] = {};
                        }
                        this.Report[Obj][Name] = d;
                    }, function (e) {
                        System.warning('获取报表发生错误');
                    }]);
            };
        }
        return Report;
    }());
    Avalon.Report = Report;
})(Avalon || (Avalon = {}));
/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
///<reference path="Avalon.ts"/>
///<reference path="Config.ts"/>
///<reference path="Index.ts"/>
var Avalon;
(function (Avalon) {
    var Router = (function () {
        function Router() {
        }
        Router.error = function () {
            console.log('Router error');
            if (typeof Config.routerError === 'function') {
                Config.routerError();
            }
        };
        Router.loadVM = function (Obj, ID, Type, Dir) {
            if (Dir === void 0) { Dir = ''; }
            console.log(Dir, Obj, Type, ID);
            if (Config.routerMap[Obj]) {
                this.load(Obj, ID, Type, Dir);
            }
            else {
                //循环添加到路由表中
                var doRouterMap_1 = function (menu) {
                    for (var _i = 0, menu_1 = menu; _i < menu_1.length; _i++) {
                        var item = menu_1[_i];
                        if (!Config.routerMap[item.Obj]) {
                            Config.routerMap[item.Obj] = {};
                        }
                        if (item.Sub.length > 0) {
                            doRouterMap_1(item.Sub);
                        }
                        if (!Config.routerMap[item.Obj][item.Type]) {
                            Config.routerMap[item.Obj][item.Type] = item;
                        }
                    }
                };
                doRouterMap_1(Menu.Menu.menu);
                this.load(Obj, ID, Type, Dir);
            }
        };
        Router.load = function (Obj, ID, Type, Dir) {
            if (Dir === void 0) { Dir = ''; }
            index.nav = avalon.mix({}, Config.routerMap[Obj][Type]);
            if (Config.routerMap[Obj]) {
                var path_1 = '';
                var vmPath = Obj + '.js';
                if (Config.routerMap[Obj][Type]) {
                    if (Config.routerMap[Obj][Type].Html) {
                        path_1 = Config.routerMap[Obj][Type].Html;
                    }
                }
                if (path_1.length < 1) {
                    if (Type) {
                        path_1 = Obj + "_" + Type + '.html';
                    }
                    else {
                        path_1 = Obj + '.html';
                    }
                }
                if (path_1.slice(-5) != '.html') {
                    path_1 += '.html';
                }
                if (Dir) {
                    path_1 = (Dir.slice(-1) == '/' ? Dir : (Dir + '/')) + path_1;
                    vmPath = (Dir.slice(-1) == '/' ? Dir : (Dir + '/')) + vmPath;
                }
                if (Config.debug) {
                    path_1 = path_1 + '?v' + new Date().getTime();
                }
                var html = Config.getHTML(Obj, Type, Dir);
                if (html) {
                    index.contentHtml = html;
                    if (typeof avalon.vmodels[Obj]['_after_' + Type] == "function")
                        avalon.vmodels[Obj]['_after_' + Type].apply(avalon.vmodels[Obj], [ID, Config.PageParams, Type]);
                    Config.loadTplSuccess(Config.TPLDir + path_1);
                }
                else {
                    Castle.Request.getHtml(Config.TPLDir + path_1, function (html) {
                        index.contentHtml = html;
                        if (typeof avalon.vmodels[Obj]['_after_' + Type] == "function")
                            avalon.vmodels[Obj]['_after_' + Type].apply(avalon.vmodels[Obj], [ID, Config.PageParams, Type]);
                        Config.loadTplSuccess(Config.TPLDir + path_1);
                    }, function (e) {
                        console.log(path_1 + '模板加载失败');
                        Config.loadTplError(Config.TPLDir + path_1);
                    });
                }
                var vm_1 = function () {
                    avalon.vmodels[Obj].Type = Type;
                    if (Config._initedVM.indexOf(Obj) == -1) {
                        avalon.vmodels[Obj].init.apply(avalon.vmodels[Obj], [ID, Config.PageParams, Type]);
                        Config._initedVM.push(Obj);
                    }
                    avalon.vmodels[Obj].ready.apply(avalon.vmodels[Obj], [ID, Config.PageParams, Type]);
                    if (typeof avalon.vmodels[Obj]['ready_' + Type] == "function")
                        avalon.vmodels[Obj]['ready_' + Type].apply(avalon.vmodels[Obj], [ID, Config.PageParams, Type]);
                };
                if (avalon.vmodels[Obj]) {
                    vm_1();
                }
                else {
                    Castle.Request.getJs(Config.VMDir + vmPath, function () {
                        if (avalon.vmodels[Obj]) {
                            vm_1();
                        }
                        else {
                            Config.loadError(Obj, Type);
                        }
                    }, function (err) {
                    });
                }
            }
            else {
                Config.routerError();
                console.log('模块加载失败');
            }
        };
        Router.ready = function () {
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}\/{id:int}', function (Obj, ID) {
                // console.log(Obj,ID)
                Avalon.Router.loadVM(Obj, ID, '');
            });
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}\/{Type:[A-Z][a-z0-9]+}\/{id:int}', function (Obj, Type, ID) {
                // console.log(Obj,ID)
                Avalon.Router.loadVM(Obj, ID, Type);
            });
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}_{Type:[A-Z][a-z0-9]+}\/{id:int}', function (Obj, Type, ID) {
                Avalon.Router.loadVM(Obj, ID, Type);
            });
            avalon.router.add('\/{Dir:[A-Z][a-z0-9]+}\/{Obj:[A-Z][a-z0-9]+}_{Type:[A-Z][a-z0-9]+}\/{id:int}', function (Dir, Obj, Type, ID) {
                Avalon.Router.loadVM(Obj, ID, Type, Dir);
            });
            avalon.router.error(this.error);
            avalon.history.start({
                root: "/"
            });
        };
        return Router;
    }());
    Router.routerMap = {};
    Avalon.Router = Router;
})(Avalon || (Avalon = {}));
/**
 * Created by 鄢鹏权 on 2017/04/07.
 */
var VType;
(function (VType) {
    VType[VType["INT"] = 1] = "INT";
    VType[VType["STRING"] = 2] = "STRING";
    VType[VType["ARRAY"] = 3] = "ARRAY";
    VType[VType["EMAIL"] = 4] = "EMAIL";
    VType[VType["URL"] = 5] = "URL";
    VType[VType["MONEY"] = 6] = "MONEY";
    VType[VType["IN"] = 7] = "IN";
    VType[VType["BOOL"] = 8] = "BOOL";
    VType[VType["INT_PLUS"] = 9] = "INT_PLUS";
    VType[VType["INT_ZERO"] = 16] = "INT_ZERO";
    VType[VType["INT_NEGATIVE"] = 17] = "INT_NEGATIVE";
    VType[VType["TIMESTAMP"] = 18] = "TIMESTAMP";
    VType[VType["DATE"] = 19] = "DATE";
    VType[VType["NULL"] = 20] = "NULL";
    VType[VType["OBJECT"] = 21] = "OBJECT";
})(VType || (VType = {}));
var VWay;
(function (VWay) {
    /**
     * 必填
     */
    VWay[VWay["MUST"] = 1] = "MUST";
    VWay[VWay["KEY"] = 2] = "KEY";
    VWay[VWay["TYPE"] = 3] = "TYPE";
    VWay[VWay["MSG"] = 4] = "MSG";
    VWay[VWay["VALUE"] = 5] = "VALUE";
    VWay[VWay["BETWEEN"] = 6] = "BETWEEN";
})(VWay || (VWay = {}));
var Validate = (function () {
    function Validate() {
    }
    Validate.v = function (Config, Params) {
        for (var _i = 0, Config_1 = Config; _i < Config_1.length; _i++) {
            var x = Config_1[_i];
        }
    };
    return Validate;
}());
var Wechat = (function () {
    function Wechat() {
    }
    Wechat.previewImage = function (Current, URLs) {
        if (URLs === void 0) { URLs = []; }
        if (URLs.length < 1) {
            URLs.push(Current);
        }
        if (URLs.indexOf(Current) == -1) {
            URLs.push(Current);
        }
        wx.previewImage(Current, URLs);
    };
    /**
     * 监听回调
     * @param event
     * @param func
     */
    Wechat.on = function (event, func) {
        Wechat.Callback[event].push([this, func]);
    };
    ;
    /**
     * 触发回调
     * @param event
     * @param data
     */
    Wechat.fire = function (event, data) {
        if (Wechat.Callback[event] instanceof Array) {
            for (var i = 0; i < Wechat.Callback[event].length; i++) {
                if (Wechat.Callback[event][i][1] instanceof Function) {
                    Wechat.Callback[event][i][1].apply(this, [data]);
                }
            }
        }
    };
    return Wechat;
}());
Wechat.WechatUser = {};
Wechat.Config = {};
Wechat.Callback = {
    config: [],
    user: [],
    chooseImage: [],
    uploadImage: [],
};
Wechat.config = function (Server, AppID, WechatID, Debug, Location) {
    if (Debug === void 0) { Debug = false; }
    if (Location === void 0) { Location = ''; }
    if (wx) {
        Castle.Request.post('http://' + Server + '/w.php?i=Js/config', {
            ID: WechatID,
            APIs: [
                'checkJsApi',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
                'translateVoice',
                'startRecord',
                'stopRecord',
                'onRecordEnd',
                'playVoice',
                'pauseVoice',
                'stopVoice',
                'uploadVoice',
                'downloadVoice',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getNetworkType',
                'openLocation',
                'getLocation',
                'hideOptionMenu',
                'showOptionMenu',
                'closeWindow',
                'scanQRCode',
                'chooseWXPay',
                'openProductSpecificView',
                'addCard',
                'chooseCard',
                'openCard'
            ],
            Debug: Debug,
            URL: Location ? Location : window.location.href
        }, function (data) {
            Wechat.Config = data;
            wx.config(data);
            Wechat.fire('config', data);
            Castle.Request.get('http://' + Server + '/w.php?i=Js/getLogined', function (user) {
                if (false === user) {
                    window.location.href = 'http://' + Server + '/w.php?i=Js/user&ID=' + WechatID;
                }
                else {
                    Wechat.fire('user', user);
                    Wechat.WechatUser = user;
                }
            });
        });
    }
    else {
        alert('请使用微信打开链接');
    }
};
Wechat.upload = function (id, success) {
    wx.uploadImage({
        localId: id,
        isShowProgressTips: 1,
        success: function (res) {
            var data = {
                id: id,
                url: res.serverId
            };
            Wechat.fire('uploadImage', data);
            if (success instanceof Function) {
                success.apply(this, [data]);
            }
        }
    });
};
Wechat.chooseImage = function (Count, SizeType, SourceType, success, error) {
    if (Count === void 0) { Count = 1; }
    if (SizeType === void 0) { SizeType = ['original', 'compressed']; }
    if (SourceType === void 0) { SourceType = ['album', 'camera']; }
    if (success === void 0) { success = null; }
    if (error === void 0) { error = null; }
    wx.chooseImage({
        count: Count,
        sizeType: SizeType,
        sourceType: SourceType,
        success: function (res) {
            var data = {
                Success: res.errMsg == 'chooseImage:ok',
                LocalIDs: res.localIds
            };
            Wechat.fire('ChooseImage', data);
            if (res.errMsg == 'chooseImage:ok') {
                if (success instanceof Function) {
                    success.apply(this, [data]);
                }
            }
            else {
                if (error instanceof Function) {
                    error.apply(this, [data]);
                }
            }
        }
    });
};